package com.farm.web.service.impl;

import com.farm.entity.PageResult;
import com.farm.farming.pojo.Cust_role;
import com.farm.util.MD5Utils;
import com.farm.web.dao.CustUserMapper;
import com.farm.web.pojo.CustUser;
import com.farm.web.service.CustUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CustUserServiceImpl implements CustUserService {

    public static final String login = "login";

    @Autowired
    private CustUserMapper custUserMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加用户
     *
     * @param custUser
     * @return
     */
    @Override
    public void addUser(CustUser custUser, Integer[] roleIds) {
        String s = MD5Utils.BCrypt("123456");
        custUser.setPassword(s);
        custUser.setStatus("2");//0为停用，1为正常启用，2为首次登录
        custUser.setType("1");//默认为普通角色
        custUserMapper.insertSelective(custUser);
        List<Cust_role> cust_roleList = new ArrayList<>();

        if (roleIds != null) {
            //获取传来的角色id
            for (Integer roleId : roleIds) {
                //查询当前添加的用户的id
                Integer id = custUser.getId();
                //根据用户的id查出用户与角色的中间表
                //custUserMapper.selectUserAndRole(id);
                //在中间表中添加传来的角色id
                custUserMapper.addUserAndRole(id, roleId);

            }
        }


    }

    /**
     * 修改用户密码
     *
     * @param custUser
     */
    @Override
    public void updatepassword(CustUser custUser, String newPassword) {
        //获取传进来的用户名
        String username = custUser.getUsername();
        //获取传进来的用户密码
        String password = custUser.getPassword();
        Example example = new Example(CustUser.class);
        Example.Criteria criteria = example.createCriteria();
        //根据username去数据库查询该用户
        criteria.andEqualTo("username", username);
        List<CustUser> custUsers = custUserMapper.selectByExample(example);
        //获取该用户的参数
        CustUser custUser1 = custUsers.get(0);
        //判断传进来的密码是否正确
        boolean b = MD5Utils.myMatches(custUser.getPassword(), custUser1.getPassword());
        if (b == false) {
            throw new RuntimeException("旧密码错误");
        }
        if (newPassword == null) {
            throw new RuntimeException("新密码不能为空");
        }
        //判断新密码和旧密码是否一致
        if (newPassword.equals(custUser.getPassword())) {
            throw new RuntimeException("新密码不能与旧密码重复");
        }
        //对新密码进行加密
        String s = MD5Utils.BCrypt(newPassword);
        //把新密码添加到用户里面
        custUser1.setPassword(s);
        //修改用户
        custUserMapper.updatePassword(custUser1);
    }

    @Override
    public void deleteUser(Integer id) {
        int count = custUserMapper.selectUserAndRole(id);
        //判断用户有没有角色
        if (count != 0) {
            //删除角色和用户的中间表
            custUserMapper.deleteUserAndRole(id);
        }
        CustUser custUser = custUserMapper.selectByPrimaryKey(id);
        custUser.setStatus("0");//修改用户的状态为停用
        custUserMapper.updateByPrimaryKey(custUser);

    }

    //根据用户名单一查询
    public CustUser findUser(String username) {
        CustUser custUser = new CustUser();
        custUser.setUsername(username);
        CustUser custUser1 = custUserMapper.selectOne(custUser);
        return custUser1;

    }

    //重置密码
    @Override
    public void resetPassword(String username) {
        CustUser custUser = new CustUser();
        custUser.setUsername(username);
        CustUser custUser1 = custUserMapper.selectOne(custUser);
        String s = MD5Utils.BCrypt("123456");
        custUser1.setPassword(s);
        custUserMapper.updateByPrimaryKey(custUser1);
    }

    @Override
    public boolean login(CustUser custUser) {
        String username1 = custUser.getUsername();
        if (redisTemplate.opsForValue().get(username1) != null) {
            // Long i= (Long) redisTemplate.opsForValue().get(username1);
            String o = (String) redisTemplate.opsForValue().get(username1 + login);
            int i = Integer.parseInt(o.toString());
            if (i > 5) {
                throw new RuntimeException("账号重试密码超过上限，请稍后重试");
            } else {
                redisTemplate.opsForValue().increment(username1 + login, 1);
            }

        } else {
            redisTemplate.opsForValue().set(username1 + login, 0, 2, TimeUnit.HOURS);
        }
        String username = custUser.getUsername();
        CustUser custUser1 = new CustUser();
        custUser1.setUsername(username);
        CustUser custUser2 = custUserMapper.selectOne(custUser1);
        custUser1.setPassword(custUser.getPassword());
        boolean b = MD5Utils.myMatches(custUser1.getPassword(), custUser2.getPassword());

        if (b == false) {
            throw new RuntimeException("账号或密码错误请重试");
        } else {
            if ("0".equals(custUser2.getStatus())) {
                throw new RuntimeException("登录用户已被停用");
            } else {
                redisTemplate.delete(custUser.getUsername());
                return true;
            }
        }


    }

    @Override
    public PageResult findAll(String customer_id, Map<String, String> map, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = new Example(CustUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (map != null) {
            if (map.get("name") != null && !"".equals(map.get("name"))) {
                criteria.andLike("name", "%" + map.get("name") + "%");
            }
            if (map.get("status") != null && !"".equals(map.get("status"))) {
                criteria.andEqualTo("status", map.get("status"));
            }

        }
        criteria.andEqualTo("customer_id", customer_id);

        Page<CustUser> custUsers = (Page<CustUser>) custUserMapper.selectByExample(example);

        for (CustUser custUser : custUsers) {
            custUser.setPassword(null);
        }


        return new PageResult(custUsers.getTotal(), custUsers.getResult());
    }


}
